package com.task.core.service.impl;

import java.util.List;
import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import com.task.common.annotation.DataScope;
import com.task.common.domain.info.KeyAndValue;
import com.task.common.exception.ServiceException;
import com.task.common.utils.SecurityUtils;
import com.task.common.utils.uuid.UUID;
import com.task.core.domain.AffiliateInfo;
import com.task.core.dto.request.AffiliateRequestDTO;
import com.task.core.mapper.AffiliateMapper;
import com.task.core.service.AffiliateService;

/**
 * @author 迪迦.
 * @date 2024/10/30 15:08
 */
@Service("AffiliateService")
public class AffiliateServiceImpl implements AffiliateService {

  @Resource
  private AffiliateMapper affiliateMapper;

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<AffiliateInfo> getAffiliateByPage(AffiliateRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    return affiliateMapper.getAffiliateByPage(request);
  }

  @Override
  public AffiliateInfo getAffiliateByCodeOrName(String code, String name) {
    return affiliateMapper.getAffiliateByCodeOrName(code, name);
  }

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<KeyAndValue> getAffiliateForOption(AffiliateRequestDTO request) {
    return affiliateMapper.getAffiliateForOption(request);
  }

  @Override
  public void addAffiliate(AffiliateRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    request.setCode(UUID.randomUUID().toString().replace("-", ""));
    affiliateMapper.addAffiliate(request);
  }

  @Override
  public void modifyAffiliate(AffiliateRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    Integer integer = affiliateMapper.modifyAffiliate(request);
    if(integer == 0) {
      throw new ServiceException("code不存在");
    }
  }

  @Override
  public void deleteAffiliate(String affiliateCode, Long userId) {
    if (affiliateMapper.getUsedCount(affiliateCode) > 0) {
      throw new ServiceException("有关联当前联盟的任务,不允许删除");
    }
    Integer delete = affiliateMapper.deleteAffiliate(affiliateCode, userId);
    if(delete == 0) {
      throw new ServiceException("code不存在");
    }
  }

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public AffiliateInfo getAffiliateByCode(String affiliateCode) {
    AffiliateRequestDTO affiliateInfo = new AffiliateRequestDTO();
    affiliateInfo.setCode(affiliateCode);
    return affiliateMapper.getAffiliateByCode(affiliateInfo);
  }
}
